package com.sunnyweather.android.ui.place

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.location.AMapLocationClient
import com.sunnyweather.android.MainActivity
import com.sunnyweather.android.R
import com.sunnyweather.android.SunnyWeatherApplication
import com.sunnyweather.android.databinding.SearchPlaceFragmentLayoutBinding
import com.sunnyweather.android.logic.Repository
import com.sunnyweather.android.logic.model.Place
import com.sunnyweather.android.logic.service.AMapPositionService
import com.sunnyweather.android.logic.util.AMapPrivacyClaim
import com.sunnyweather.android.logic.util.LogUtil
import com.sunnyweather.android.ui.weather.WeatherActivity

class PlaceSearchFragment:Fragment() {

    //计算属性，动态获取ViewBinding对象
    val searchPlaceFragmentLayoutBinding :SearchPlaceFragmentLayoutBinding
    get() = _searchPlaceFragmentLayoutBinding!!
    private var _searchPlaceFragmentLayoutBinding:SearchPlaceFragmentLayoutBinding?=null
    val placeViewModel by lazy { ViewModelProvider(this).get(PlaceViewModel::class.java) }
    private lateinit var adapter: PlaceAdapter
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _searchPlaceFragmentLayoutBinding=SearchPlaceFragmentLayoutBinding.inflate(inflater,container,false)
        return searchPlaceFragmentLayoutBinding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)



        LogUtil.d("PlaceFragment.isPlaceStored","${placeViewModel.isPlaceStored()}")
        if(activity is MainActivity && placeViewModel.isPlaceStored()){
                jumpToWeather()
        }


        searchPlaceFragmentLayoutBinding.recycleView.layoutManager=LinearLayoutManager(this.context)
        adapter= PlaceAdapter(this,placeViewModel.placeList)
        searchPlaceFragmentLayoutBinding.recycleView.adapter=adapter
        searchPlaceFragmentLayoutBinding.searchPlaceEditText.addTextChangedListener {
            val query=it.toString()
            if(query.isEmpty()){
                searchPlaceFragmentLayoutBinding.bgImageView.visibility=View.VISIBLE
                searchPlaceFragmentLayoutBinding.recycleView.visibility=View.GONE
                placeViewModel.placeList.clear()
                adapter.notifyDataSetChanged()
            }else{
                //搜索框不为空就发起查询请求
                placeViewModel.queryPlaces(query)
            }
        }
        placeViewModel.placeLiveData.observe(viewLifecycleOwner){result->
            if(result.isSuccess){
                val places=result.getOrThrow()
                if(!places.isEmpty()){
                    //如果有查询结果，就将查询结果显示出来
                    searchPlaceFragmentLayoutBinding.recycleView.visibility=View.VISIBLE
                    //searchPlaceFragmentLayoutBinding.bgImageView.visibility=View.GONE
                    placeViewModel.placeList.clear()
                    placeViewModel.placeList.addAll(places)
                    adapter.notifyDataSetChanged()
                }else{
                    //如果没有，就提示用户并清空列表
                    Toast.makeText(this.context,"没有查询结果",Toast.LENGTH_SHORT).show()
                    searchPlaceFragmentLayoutBinding.recycleView.visibility=View.GONE
                    placeViewModel.placeList.clear()
                    adapter.notifyDataSetChanged()
                }
            }else{
                Toast.makeText(this.context,"查询失败！",Toast.LENGTH_SHORT).show()
                searchPlaceFragmentLayoutBinding.recycleView.visibility=View.GONE
                placeViewModel.placeList.clear()
                adapter.notifyDataSetChanged()
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //视图销毁时viewBinding也应该释放
        _searchPlaceFragmentLayoutBinding=null
    }

    fun jumpToWeather(){
        val restoredPlace=placeViewModel.getRestoredPlace()
        if(restoredPlace!=null) {
            if(restoredPlace.name!="location Error"){
                val intent = Intent(this.context, WeatherActivity::class.java).apply {
                    putExtra("place_lat", restoredPlace.location.lat)
                    putExtra("place_lng", restoredPlace.location.lng)
                    putExtra("place_name", restoredPlace.name)
                }
                startActivity(intent)
                activity?.finish()
            }
        }else{
            Toast.makeText(this.context,"定位失败！请确认已正确授予定位权限",Toast.LENGTH_SHORT).show()
        }
    }
}